package com.ssm.interceptor;

import com.ssm.entity.SysPer;
import com.ssm.entity.SysUser;
import com.ssm.exception.PrivilegesException;
import com.sun.xml.internal.bind.v2.runtime.reflect.opt.Const;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

public class AuthFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        System.out.println("权限拦截器启动");
        //        获取到请求路径
        String URL = httpServletRequest.getRequestURI();
        System.out.println(URL);
//创建数组，将数据库中需要访问的页面加入，如果访问的不是这些页面不需要拦截，！！存在隐患，最好解决方法，将所有页面都要加入数据库
        List<String> surl=new ArrayList<>();
        surl.add("/showList");
        surl.add("/notice");
        surl.add("/showcolumn");
        surl.add("/showComments");
        surl.add("/elcBlack/index1");
        surl.add("/roleManage");
        for(String str : surl){
            if(!URL.contains(str)){
               return true;
            }
        }
        HttpSession session = httpServletRequest.getSession();
        SysUser sysUser = (SysUser) session.getAttribute("sysUser");
        boolean flag = false;
        if (sysUser!=null){
            List<SysPer> sysPer = sysUser.getSysPers();
            for (SysPer sys :sysPer){
                if (URL.contains(sys.getUrl())){
                    flag = true;
                }
            }
            if (!flag) {
                throw  new PrivilegesException();
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
